package com.hevery.web.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @Author: Hevery
 * @Description:
 * @Date: Created on 2017/10/7
 * @Modified By:
 */
//@Component
public class TimeInterceptor implements HandlerInterceptor{
    /**Controller访问之前，调用该方法;参数handler表示真正用来处理请求的方法的声明*/
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        System.out.println("preHandle");
        System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
        System.out.println(((HandlerMethod)handler).getMethod().getName());
        httpServletRequest.setAttribute("startTime",System.currentTimeMillis());
        return true;
    }

    /**控制器的方法调用之后，调用该方法；但是发生异常时不会调用该方法*/
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
        Long start = (Long)httpServletRequest.getAttribute("startTime");
        System.out.println("time interceptor 耗时："+ (System.currentTimeMillis() - start));
    }

    /**不管发不发生异常，最终都会调用此方法*/
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterComletion");
        Long start = (Long)httpServletRequest.getAttribute("startTime");
        System.out.println("time interceptor 耗时："+ (System.currentTimeMillis() - start));
        System.out.println("Exception is :"+e);
    }
}
